﻿using System;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web.Security;
using System.Web.UI;
using EmptyWallGallery.Core;
using EmptyWallGallery.Core.Utilities;

namespace EmptyWallGallery.FrontEnd.inside.Editor.Articles
{
    public partial class Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack) return;

            BindDrop();
            BindGrid();

            Page.Title = "Quản lý tin bài - " + Configs.WebTitle;
        }

        public void BindDrop()
        {
            DropCategory.DataSource = Core.BLL.Categories.Instance.GetParentCat(0, 0);
            DropCategory.DataTextField = "Title";
            DropCategory.DataValueField = "CatID";
            
            DropCategory.DataBind();
            DropCategory.Items.Insert(0, "-- Tất cả --");

            if (Request.QueryString["CatId"] != null)
            {
                DropCategory.SelectedValue = Request.QueryString["CatId"] == "0" ? "-- Tất cả --" : Request.QueryString["CatId"];
            }

            drpUser.DataSource = Membership.GetAllUsers();
            drpUser.DataBind();
            drpUser.Items.Insert(0, "-- Tất cả --");
        }

        public void BindGrid()
        {
            switch (Request.QueryString["action"])
            {
                case "Delete":
                    //Delete
                    if (Request.QueryString["ID"] != null)
                    {
                        if (Common.Instance.IsNumeric(Request.QueryString["ID"]))
                        {
                            DeleteArticle(int.Parse(Request.QueryString["ID"]));

                            Response.Redirect(Request.QueryString["ReUrl"] ?? "default.aspx", false);
                        }                        
                    }
                    break;
                case "Search":
                    var title = Request.QueryString["Title"];
                    var catId = int.Parse(Request.QueryString["CatId"]);
                    var status = int.Parse(Request.QueryString["Status"]);
                    var fromDay = Request.QueryString["FromDay"];
                    var toDay = Request.QueryString["ToDay"];
                    var userId = Request.QueryString["UserId"] == string.Empty ? Guid.Empty : Guid.Parse(Request.QueryString["UserId"]);

                    var item = Core.BLL.Articles.Instance.Search(title, catId, userId, status, fromDay, toDay);
                    grdListArticle.DataSource = item;
                    grdListArticle.DataBind();

                    dyntable_length.InnerHtml = "Tìm thấy <b>" + item.Count + "</b> bài viết.";
                    txtTitle.Text = title;

                    DropCategory.SelectedValue = catId == 0 ? "-- Tất cả --" : Convert.ToString(catId);
                    drpUser.SelectedValue = userId == Guid.Empty ? "-- Tất cả --" : Membership.GetUser(userId).UserName;
                    drpStatus.SelectedValue = Convert.ToString(status);
                    //txtFromDay.Text = fromDay;
                    //txtToDay.Text = toDay;
                    
                    ScriptManager.RegisterClientScriptBlock(this, GetType(), "Test",
                                                "$('input:radio, select.uniformselect').uniform();", true);
                    break;
                default:
                    //using (var dc = new ZozoGameDataContext(Configs.ConnectionString))
                    //{
                    //    grdListArticle.DataSource = dc.Justin_Product_GetAll(1);
                    //    grdListArticle.DataBind();
                    //}
                    break;
            }
        }

        private static void DeleteArticle(int articleId)
        {
            var objArticle = Core.BLL.Articles.Instance.GetByEdit(articleId);

            Common.Instance.DeleteFile(Configs.ArticleFile + "ListFile\\" +
                                                      DateTime.Parse(objArticle.ReleaseDate.ToString()).Year + "\\" +
                                                      Common.Instance.Right(
                                                          "0" + DateTime.Parse(objArticle.ReleaseDate.ToString()).Month,
                                                          2) + "\\" +
                                                      Common.Instance.Right(
                                                          "0" + DateTime.Parse(objArticle.ReleaseDate.ToString()).Day, 2) +
                                                      "\\" +
                                                      objArticle.ArticlesId + ".xml");

            Core.BLL.Articles.Instance.Delete(articleId);
        }

        public string DisplayCategory(string articleId)
        {
            return Core.BLL.Articles.Instance.GetAllCat(0, int.Parse(articleId));
        }

        /// <summary>Display Title and Cut if too long</summary>
        /// <param name="title">String Title to display</param>
        /// <returns></returns>
        /// <remarks></remarks>
        public string DisplayTitle(string title)
        {
            string strOut;
            if (title.Length > 62)
            {
                strOut = title.Substring(0, 62) + "...";
            }
            else
            {
                strOut = title;
            }
            return strOut;
        }

        //protected string DisplayStatus(object approved)
        //{
        //    return Convert.ToBoolean(approved) ? "Đã đăng" : "Chưa đăng";
        //}

        public object DisplayStatusDate(object b, string d)
        {
            string str;
            var dDate = DateTime.Parse(d).AddHours(Configs.TimeLine);
            if (!(bool)b)
            {
                str = string.Format("{0:dd/MM/yyyy}", dDate) + "<br />Đã đăng";
            }
            else
            {
                if (dDate > DateTime.Now.AddHours(Configs.TimeLine))
                {
                    str = string.Format("{0:dd/MM/yyyy}", dDate) + "<br />Đã hẹn giờ";
                }
                else
                {
                    str = string.Format("{0:dd/MM/yyyy}", dDate) + "<br />";
                }
            }
            return str;
        }

        protected void BtnApplyClick(object sender, EventArgs e)
        {
            const int i = 0;
            if (Request.Form["selectedAction0"] == "1" | Request.Form["selectedAction1"] == "1")
            {
                //Edit Category
                var vId = "";
                foreach (var str in Regex.Split(Request.Form["cboCheckArticle"], ",").Where(str => i == 0))
                {
                    vId = str;
                    if (!Common.Instance.IsNumeric(vId))
                    {
                        vId = "1";
                    }
                    break; // TODO: might not be correct. Was : Exit For
                }
                Response.Redirect("ArticleUpdate.aspx?action=Edit&ID=" + vId + "&ReUrl=" + Request.RawUrl, false);
            }
            else if (Request.Form["selectedAction0"] == "2" || Request.Form["selectedAction1"] == "2")
            {
                //Delete
                foreach (var str in Regex.Split(Request.Form["cboCheckArticle"], ","))
                {
                    DeleteArticle(int.Parse(str));
                }
                BindGrid();
            }
        }

        protected void BtnApply2Click(object sender, EventArgs e)
        {
            BtnApplyClick(sender, e);
        }

        protected void GrdListArticlePageIndexChanging(object sender, System.Web.UI.WebControls.GridViewPageEventArgs e)
        {
            grdListArticle.PageIndex = e.NewPageIndex;
            BindGrid();
        }

        protected void BtnSearchClick(object sender, EventArgs e)
        {
            DateTime datetime1;
            DateTime datetime2;
            var title = txtTitle.Text.Length == 0 ? string.Empty : txtTitle.Text;
            var catId = DropCategory.SelectedValue == "-- Tất cả --" ? 0 : int.Parse(DropCategory.SelectedValue);
            var status = drpStatus.SelectedValue;
            //var fromDay = DateTime.TryParse(txtFromDay.Text, out datetime1) ? datetime1.ToString() : string.Empty;
            //var toDay = DateTime.TryParse(txtToDay.Text, out datetime2) ? datetime2.ToString() : string.Empty;
            var userId = drpUser.SelectedValue == "-- Tất cả --"
                         ? string.Empty
                         : Membership.GetUser((string) drpUser.SelectedValue).ProviderUserKey.ToString();

            Response.Redirect("?action=Search&Title=" + title + 
                "&CatId=" + catId +
                "&UserId=" + userId +
                "&Status=" + status +
                "&FromDay=&ToDay=");
        }
    }
}